import { Controller, Get, Query, Res } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiQuery } from '@nestjs/swagger';
import logger from 'src/common/utils/log';
import { PlayerSignupExportService } from '../service/player-signup-export.service';
import { Response } from 'express';
import { Auth } from 'src/common/decorators/auth.decorator';
import { RequirePermission } from 'src/common/decorators/permission.decorator';

@Auth()
@ApiBearerAuth()
@Controller('player-signup')
export class PlayerSignupExportController {
  constructor(private readonly excelExportService: PlayerSignupExportService) {}

  @ApiOperation({ summary: '导出选手信息到 Excel 文件' })
  @ApiQuery({ name: 'tournamentId', type: Number, description: '赛事 ID' })
  @ApiQuery({
    name: 'categoryId',
    type: Number,
    description: '类别 ID',
    required: false,
  })
  @ApiQuery({
    name: 'eventId',
    type: Number,
    description: '赛事项目 ID',
    required: false,
  })
  @ApiQuery({
    name: 'stageIndex',
    type: Number,
    description: '阶段索引',
    required: false,
    default: 1,
  })
  @RequirePermission('1002002')
  @Get('exportPlayers')
  async exportPlayers(
    @Res() res: Response,
    @Query('tournamentId') tournamentId: number,
    @Query('categoryId') categoryId?: number,
    @Query('eventId') eventId?: number,
    @Query('stageIndex') stageIndex: number = 1,
  ) {
    try {
      // 假设这里获取所有选手数据
      const excelBuffer = await this.excelExportService.exportPlayersToExcel({
        tournamentId,
        categoryId,
        eventId,
        stageIndex,
      });
      res.set({
        'Content-Type':
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'Content-Disposition': 'attachment; filename=players.xlsx',
        'Content-Length': excelBuffer.byteLength,
      });

      res.end(excelBuffer);
    } catch (error) {
      logger.error('导出 Excel 失败', error);
      res.status(500).send('导出 Excel 失败');
    }
  }
}
